package com.spark.core;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.exceptions.PersistenceException;

import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException;
import com.spark.util.MemcachedHelper;

public class SparkActionService extends SparkServlet {

	private static final long serialVersionUID = 1439184998611090718L;

	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = null;
		try {
			initRequestAndResponse(request, response);
			response.setContentType(SparkConfiguration.CONTENT_TYPE_JSON);
			String path = getServicePath(request);
			if (path != null) {
				String[] args = path.split("/");
				String action = args[1];
				if(action!=null && !"".equals(action)){
					SparkContext context =  new SparkContext(SparkConfiguration.getInstance());
					initContext(context,request,response);
					
					SparkConfiguration configuratin = context.getSparkConfiguration();
					boolean isCheckSession = configuratin.isCheckActionSession(action);
					if(isCheckSession){
						String suk = request.getParameter(SparkContext.SPARK_USER_KEY);			
						if(suk == null || MemcachedHelper.get(suk) == null){
							out = response.getWriter();
							Message message = new Message(false);
							message.sessionTimeOut();
							JacksonMapper.getInstance().writeValue(out, message);
							return;
						}
					}
					
					Object act = configuratin.getActionInstance(action);
					String method = configuratin.getActionMethod(action);
					
					//TODO:判断act method
					if(act == null) throw new Exception("未找到 "+action + " 的action!");
					Method m = act.getClass().getMethod(method,new Class[]{SparkContext.class}); 
					m.invoke(act,new Object[]{context});		
				}
			}
		} catch (InvocationTargetException  e) {
			//TODO:重构异常处理部分
			Message message = new Message(false);
			if(e.getTargetException() instanceof SparkException){
				SparkException se = (SparkException)e.getTargetException();
				message.setError("<div style='font-size:13px;'>系统发生一个错误,请联系系统管理员!<br/>错误号 :  <b style='color:red'>"+se.getErrorId()+"</b></div>");
				message.setWidth(350);
				message.setHeiht(170);
			}else if(e.getTargetException() instanceof PersistenceException){
				PersistenceException pe = (PersistenceException)e.getTargetException();
				if(pe.getCause() instanceof CommunicationsException) {
					message.setError("数据库连接异常!");
					message.setWidth(350);
					message.setHeiht(170);
				}else{
					e.printStackTrace();
					message.setError(e.toString());
				}
			}else{
				e.printStackTrace();
				message.setError(e.toString());
			}
			out = response.getWriter();
			JacksonMapper.getInstance().writeValue(out, message);
		} catch(Exception e){
			//TODO:log4j记录一下?
			Message message = new Message(false);
			e.printStackTrace();
			message.setError(e.toString());
			out = response.getWriter();
			JacksonMapper.getInstance().writeValue(out, message);
		} finally {
			if (out != null)
				out.close();
		}
	}

	
}
